import store from '@/store'
import { getKey } from '@/utils/storage'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { emitter, logout } from '@/utils/util'
import { ON_LINE_USER } from '@/utils/eventBusName'

/**
 * websocket
 */
export function connectWebSocket () {
  if (!store.state.network.ws) {
    store.commit('changeWsInstance', new WebSocket(process.env.VUE_APP_WEBSOCKET_URL + '?token=' + getKey('tokenValue')))
    store.state.network.ws.onopen = function () {
      console.log('websocket连接成功')
      store.state.network.ws.send('发送一个测试数据')
      store.commit('changeWebsocketReconnectNum', 1)
    }
    store.state.network.ws.onmessage = function (event) {
      console.log('数据已接收...', event.data)
      const data = JSON.parse(event.data)
      if (data.code === 200) {
        ElNotification({
          title: '推送消息',
          message: data.data,
          position: 'bottom-right',
          duration: 0,
          dangerouslyUseHTMLString: true
        })
      } else if (data.code === 407) {
        ElMessageBox.alert(data.message, '账号被挤提醒', {
          confirmButtonText: '重新登录',
          callback: () => {
            logout()
          }
        })
      } else if (data.code === 211) {
        console.error('emitOnLine--', data.data)
        // 切换到宏任务，防止头部还没有注册事件到eventBus Map中。
        setTimeout(() => {
          emitter.emit(ON_LINE_USER, data.data)
        }, 0)
      }
    }
    store.state.network.ws.onclose = function () {
      console.log('websocket连接异常，您将无法接收到实时数据')
    }
    store.state.network.ws.onerror = function () {
      store.commit('changeWsInstance', null)
      if (store.state.network.websocketReconnectNum < store.state.network.maxWebsocketReconnectNum) {
        store.state.network.websocketReconnectNum++
        setTimeout(() => {
          connectWebSocket()
        }, 3000)
      } else {
        ElMessage.warning('websocket连接异常，您将无法接收到实时数据')
      }
    }
  }
}
